import gc
import os
import sys
import weakref
from os.path import getsize

import cv2
import paddle
from flask import Blueprint, request
from paddleocr import PaddleOCR

import psutil
import os

from common.response import success

def has_gpu():
    """判断是否有可用的GPU（针对PaddlePaddle）"""
    try:
        # 检查是否编译了GPU支持
        if not paddle.is_compiled_with_cuda():
            return False
        # 检查是否有可用的GPU设备
        return paddle.device.cuda.device_count() > 0
    except Exception as e:
        print(f"检查GPU时出错: {e}")
        return False

# 创建一个蓝图对象
bp = Blueprint('bp', __name__)

ocr = PaddleOCR(use_angle_cls=True, use_doc_orientation_classify=False,
                use_doc_unwarping=False,
                use_textline_orientation=False, lang="ch", use_gpu=has_gpu(), show_log=False, enable_mkldnn=False)  # need to run only once to download and load model into memory
@bp.route("/ocr", methods=["POST"])
def upload_file():
    if 'file' not in request.files:
        raise Exception("请上传文件")

    file = request.files['file']
    # 如果用户没有选择文件，浏览器也会提交一个没有文件名的空部分
    if file is None or file.filename == '':
        raise Exception("请上传文件")

    result = ocr.ocr(file.read(), cls=True)

    return_data = []

    for idx in range(len(result)):
        res = result[idx]
        if res is None:
            continue
        for line in res:
            return_data.append({
                "text": line[1][0],
                "confidence": line[1][1],
                # "box": line[0]
            })

    del result[:]

    gc.collect()
    print(u'当前进程的内存使用：%.4f GB' % (psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024 / 1024))

    return success(data=return_data)
